<template>
  <div class="cmsUploadFile" :class="disabled?'noneBtn':''" style="margin-top: 5px">
    <el-upload class="upload-demo fill span18 small-payment-upload" :before-upload="(file)=>uploadPartOne(file)" action multiple :show-file-list="false" :before-remove="(file,fileListA)=>removeFile(file,fileListA,fileSystem.part)" :file-list="list" :disabled="disabled">
      <div>
        <el-button v-if="!disabled" size="small" :loading="isLoading" type="primary">
          <i class="iconfont icon-shangchuan"></i> 点击上传
        </el-button>
      </div>
      <div slot="tip" v-if="!disabled" class="el-upload__tip" style="line-height: 20px!important;">{{info}}</div>
    </el-upload>
    <div class="file">
      <div class="fileList" v-for="(item,index) in list" :key="index" :style="{display:phoneState?'black':'flex'}">
        <el-tooltip effect="dark" :content="item.realName" placement="top-start">
          <div class="fileName" @click="preview(item)">
            <img :src="$publicJs.filesTypeFilter(item.realName,'../../../')" alt="" style="display:block;width:25px;height:15px">
            <span :class='isOlder ? "realName" : ""'><i class="bg"></i>{{item.realName}}</span>
          </div>
        </el-tooltip>
        <div>
          <slot name="button" :scope="{file:item,index:index}"></slot>
          <el-button v-show="$publicJs.showPreviewBtn(item,'realName')" @click="preview(item)" type="primary" :size="isOlder ? 'medium' : 'mini'" round icon='el-icon-view'>查看</el-button>
          <el-button @click="download(item)" type="primary" :size="isOlder ? 'medium' : 'mini'" round icon='el-icon-download'>下载</el-button>
          <el-button @click="removeFile(item)" type="danger" :size="isOlder ? 'medium' : 'mini'" v-show="!disabled" round icon='el-icon-delete'>删除</el-button>
        </div>
      </div>
      <div v-for="(item,index) in addList" :key="index" :style="{display:phoneState?'black':'flex'}" class="fileList">
        <el-tooltip effect="dark" :content="item.name" placement="top-start">
          <div class="fileName">
            <img :src="$publicJs.filesTypeFilter(item.name,'../../../')" alt="" style="display:block;width:25px;height:15px">
            <span><i class="bg"></i>{{item.name}}</span>
          </div>
        </el-tooltip>
        <div>
          <slot name="button" :scope="{file:item,index:index}"></slot>
          <el-button @click="removeFile(item)" type="danger" size="mini" round icon='el-icon-delete'>删除</el-button>
        </div>
      </div>
    </div>

    <el-dialog width="1000px" :visible.sync="dialogVisible" v-dialog-drag title="视频播放" append-to-body @close="destoryVideo" :modal-append-to-body="false" :close-on-click-modal="false">
      <div class="flex-hv">
        <video id="videoPlayer" style="width: 100%;" controls :src="videoUrl"></video>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import file from '@/api/file'
import { Base64 } from 'js-base64'
const PREVIEW_URL = process.env.VUE_APP_FILE_PREVIEW
import { v4 as uuidv4 } from 'uuid';
import msgUtil from '@/utils/msgUtil'
import { addTable, editTable, deleteTable, uploadFile, preview, download, getTablePage, packZip } from '@/api/file'


export default {
  name: "cmsUploadFile",
  props: {
    isOlder: false,
    disabled: {
      type: Boolean,
      default: false
    },
    detailType: {
      type: String,
      default: ''
    },
    fileList: {
      type: Array,
      default: () => []
    },
    fileSystem: {
      type: Object,
      default: {
        sys: '',
        module: '',
        entityClass: '',
        viewByAnon: true,
        longLife: false,
        part: 'one'
      }
    },
    detailId: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'single'
      //  mul--多文件，single---单文件
    },
    info: {
      type: String,
      default: ''
      //  文件支持类型
    },
    //文件類型校验方法-若需要校验，从父组件传入此方法
    checkFiles: {
      type: Function,
      default: (file) => {
        return true
      }
    },
    //获取文件后的回调函数-从父组件传入此方法
    getFilesCb: {
      type: Function,
      default: () => { }
    },
    //获取文件后的回调函数-从父组件传入此方法
    uploadCb: {
      type: Function,
      default: () => { }
    }
  },
  watch: {
    'fileList': {
      handler (val) {
        this.list = [...val]
        console.log(this.list, 'lissssssssssssssssssst')
      },
      deep: true
    },
    'detailId': {
      handler (val, oldVal) {
        if (this.detailType !== 'build') {
          this.init()
        } else {
          this.list = []

        }
      },
      deep: true
    },
    isOlder (val) {
      this.isOlder = val
    }
  },
  data () {
    return {
      dialogVisible: false,
      videoUrl: '',
      isLoading: false,
      list: [],
      addList: [],
      phoneState: false
    }
  },
  mounted () {
    if (this.detailType !== 'build') {
      this.init()
    }
    if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
      this.phoneState = true
    } else {
      this.phoneState = false
    }
  },
  methods: {
    destoryVideo () {
      $('#videoPlayer').prop('src', '');
    },
    // 弹窗里面引用文件，需要销毁掉，防止数据串了。
    saveAll (formId) {
      console.log(this.addList)
      this.addList.forEach(it => {
        this.upload(it, this.fileSystem.part, formId)
      })
      this.addList = []
      this.list = []
    },
    cancelAll () {
      this.addList = []
      this.list = []
    },
    init () {
      this.$publicUpload.getFile(this.fileSystem.module, this.detailId, this.fileSystem.part)
        .then(res => {
          const items = res.data || []
          const arr = []
          items.forEach(o => {
            arr.push({
              realName: o.name,
              name: o.name,
              size: o.size,
              id: o.id
            })
          })
          this.list = arr
          this.change()
        })
    },

    getFile (file) {
      this.$publicUpload.checkFile(file.id)
    },
    uploadPartOne (file) {
      if (!this.checkFiles(file)) {
        return
      }
      this.addList.push(file)
      this.change()
    },
    // 上传文件前
    async upload (file, part, id) {
      if (!this.checkFiles(file)) {
        return
      }
      /*
      *公共上传方法
      * */
      // this.$set(this, 'isLoading', true)
      let formId = id || this.detailId
      if (!formId) {
        msgUtil.error2('上传文件-表单编号不能为空！')
        return
      }
      await this.$publicUpload.uploadFile(
        file,
        formId,
        this.fileSystem.module,
        part,
        file.name,
      )
        .then(async res => {
          if (res.code === 200) {
            if (this.type === 'single') {
              if (this.list.length != 0) {
                //先解绑
                await this.$publicUpload.removeFile(this.list[0].id)
                // this.list = [{
                //   realName: file.name,
                //   name: file.name,
                //   size: file.size,
                //   id: res.data[0],
                // }]
              } else {
                // this.list = [{
                //   realName: file.name,
                //   name: file.name,
                //   size: file.size,
                //   id: res.data[0],
                // }]
              }
            }
            if (this.type === 'mul') {
              // this.list.push({
              //   realName: file.name,
              //   name: file.name,
              //   size: file.size,
              //   id: res.data[0],
              // })
            }
            this.uploadCb(res)
          } else {
            msgUtil.error2(res.data.message)
          }
        })
        .catch(res => {
          this.$set(this, 'isLoading', false)
          msgUtil.error2(this.$route.name + '上传文件前-请求失败')
        })
      this.$set(this, 'isLoading', false)
      this.change()
    },
    // 删除文件时解绑文件
    removeFile (file, fileList, part) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        let isNew = false
        this.addList.forEach((item, index) => {
          if (file.uid === item.uid) {
            this.addList.splice(index, 1)
            isNew = true
          }
        })

        if (isNew) {
          this.change()
          return
        }

        if (this.type === 'mul') {
          this.list.forEach((item, index) => {
            if (file.id === item.id) {
              this.list.splice(index, 1)
            }
          })
        }
        if (this.type === 'single') {
          this.$set(this, 'list', [])
        }
        this.$publicUpload.removeFile(file.id)
        this.change()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    download (file) {
      this.$publicUpload.checkFile(file.id, file.realName)
    },
    change () {
      this.$emit('change', this.list, this.addList)
    },
    uuid () {
      return uuidv4().split('-')[0]
    },
    preview (row) {
      this.videoUrl = ''
      if (row.realName.split('.')[row.realName.split('.').length - 1].indexOf('mp4') > -1 || row.realName.split('.')[1].indexOf('avi') > -1) {
        this.$set(this, 'videoUrl', `${process.env.VUE_APP_BASE_API}/file-server/file/download?id=` + row.id)
        this.$nextTick(() => {
          this.dialogVisible = true

        })
      } else {
        //不是mp4
        this.loading = true
        this.$httpGet('/file-server/file/preview?id=' + row.id).then(response => {
          this.loading = false;
          //  如果是minio地址路径，则调用kkview
          if (!response.data.startsWith("/")) {
            window.open(PREVIEW_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(response.data)));
          } else {
            //  如果是转换后的previewGetFile，浏览器直接打开
            window.open(response.data);
          }
        }).catch(res => {
          console.log(res)
          this.loading = false;
        })
      }

    },
  }
}
</script>

<style scoped lang="scss">
.cmsUploadFile {
  /*width: 400px;*/
  .fileList {
    /*display: flex;*/
    align-items: center;
    justify-content: space-between;
    margin-bottom: 5px;
    .fileName {
      display: flex;
      align-items: center;
      cursor: pointer;
      span {
        display: block;
        width: 120px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
<style lang="scss">
.noneBtn {
  .small-payment-upload {
    display: none;
  }
}
.realName {
  font-size: 18px;
}
</style>
